package md.mru.frontend.utils;

import md.mru.core.domains.type.RolesType;
import md.mru.core.dtos.UserDto;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author MG
 * @since 29.04.2014
 */
public class AppUserDetails implements UserDetails {

    private static final long serialVersionUID = -1008450580063032158L;

    UserDto user;
    List<GrantedAuthority> roles = new ArrayList<>();

    public AppUserDetails(UserDto user) {
        this.user = user;

        if (user.getUserGroup() != null) {
            for (RolesType role : user.getUserGroup().getRolesType()) {
                roles.add(new SimpleGrantedAuthority(role.name()));
            }
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getEmail();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getEnabled();
    }

    public UserDto getUser() {
        return user;
    }
}
